<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Warehouse\Controllers;



use App\Api\Service\Warehouse\Models\OrderWarehouse;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Warehouse;
use App\Eloquent\Ygt\WarehouseBill;
use App\Eloquent\Ygt\WarehouseBillRelation;
use App\Eloquent\Ygt\WarehouseCart;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class BillController extends Controller
{
    public $userId          = 25;
    public function index(){}
    //客户的账单列表
    public function lists()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $page               = request('page',1);
        $limit              = request('page_num',10);
        $customerId         = request('customer_id',0);
        $dealStatus         = request('deal_status',0);//0全部1已处理(结清)
        $companyId         = request('company_id',0);//0全部1已处理(结清)
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        if(!$companyId){
            $companyId          = $userInfo->company_id;
        }

        $where              = [ 'company_id'=>$companyId ];
        if($customerId)
        {
            $where['customer_id']   = $customerId;
        }
        if($dealStatus == 1)
        {
            $where['deal_status']   = $dealStatus;
        }
        $column             = 'id,warehouse_bill_id,customer_id,sn,money,pay_type,created_at,status,pre_money,deal_status,deduct_money,deduct_money_regard';
        $offset             = ($page-1)*$limit;
        $collection         = \App\Eloquent\Ygt\WarehouseBillMoney::getList($where,$column,'','');
        $lists              = $collection->toArray();
        $totalMoeny         = 0;
        foreach ($lists as $key=>$val)
        {
            $totalMoeny     += $val['money'];

            $valCreatedAt   = $val['created_at'];
            $lists[$key]['created_at']  = date('Y-m-d',$valCreatedAt);

            $where          = ['warehouse_bill_id'=>$val['warehouse_bill_id']];
            $relationObj    = WarehouseBillRelation::getList($where);
            $warehouseIdArr = $relationObj->pluck('warehouse_id');
            $where          = ['id'=>['in',$warehouseIdArr]];
            $orderList      = Warehouse::getList($where)->toArray();
            $imgPathArr     = [];
            foreach($orderList as $k=>$v)
            {
                if(!empty($v['img_path']))
                {
                    $imgPathArr[]   = $v['img_path'];
                }
            }
            $lists[$key]['img_path_arr'] = $imgPathArr;
            if($userInfo['company_id'] == 2){
                $lists[$key]['money'] = '已付金额: '.$val['money'];
            }else{
                $lists[$key]['money'] = '已收金额: '.$val['money'];
            }

            //客户的账单显示应付金额
            if($userInfo['company_id'] == 2){
                $lists[$key]['pre_money'] = '应付金额: '.$val['pre_money'];
            }else{
                $lists[$key]['pre_money'] = '应收金额: '.$val['pre_money'];
            }

            if(!$lists[$key]['deduct_money']){
                $lists[$key]['deduct_money'] = 0;
            }

            if(!$lists[$key]['deduct_money_regard']){
                $lists[$key]['deduct_money_regard'] = '';
            }

            //现在单号上加状态 20181230 zhuyujun
            $status = $lists[$key]['status'];
            if($status){
                $tmpStatusList  = config('status.warehouse_bill_money_status');
                if(isset($tmpStatusList[$status])){
                    if($tmpStatusList[$status]['txt'] == '未收款核销' || $tmpStatusList[$status]['txt'] == '销售已转账'){
                        //客户特殊处理-未收款核销
                        if($userInfo['company_id'] == 2){
                            $tmpStatusList[$status]['txt'] = '收款核销';
                        }
                    }

                    $lists[$key]['pre_money'].= "【{$tmpStatusList[$status]['txt']}】";
                }

            }

            //状态兼容
            if($status == 1){
                $lists[$key]['status'] = 0;
            }
            //如果状态4、5，且收款已収齐
            if(in_array($status,[4,5,100])){
                if($val['deduct_money'] + $val['money'] == $val['pre_money']){
                    $lists[$key]['status'] = 1;
                }
            }

        }

        $totalMoeny = sprintf('%.2f',$totalMoeny );
        $result             = ['bill_list'=>$lists,'total_money'=>$totalMoeny];
        return $result;
    }
    //生成应收单 -- 改为交货单
    public function edit()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $customerId         = request('customer_id',0);
        $money              = request('money',0);
        $payType            = request('pay_type','');
        $sendTimeDate       = request('send_date','');
        //处理传入json数据
        $setPriceListJson = request('set_price_list');
        $setPriceList = [];
        if($setPriceListJson){
            $setPriceList = json_decode(htmlspecialchars_decode($setPriceListJson), true);
        }

        //处理数据，一个成品ID对应一个价格
        $warehousePriceList = [];
        if(!empty($setPriceList)){
            foreach ($setPriceList as $setPriceRow){
                $warehousePriceList[$setPriceRow['warehouse_id']] = $setPriceRow['price'];
            }
        }



        if( !$userInfo || !$customerId)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        if(!$payType)
        {
            xThrow( ERR_PARAMETER,'付款方式' );
        }
        if(!$money)
        {
            xThrow( ERR_PARAMETER,'金额' );
        }
        $companyId          = $userInfo->company_id;
        $isSubmit           = request('is_submit',1);
        if($isSubmit){
            $where              = [
                'ygt_warehouse.customer_id'=>$customerId,
                'ygt_warehouse.bill_number'=>['>',0],
            ];
            $warehouseList      = Warehouse::getList($where)->toArray();
            if(empty($warehouseList))
            {
                xThrow(ERR_PARAMETER, '尚未添加该用户的入库单');
            }
            //检测添加数量是否超过了库存中的数量
            $numberResult           = true;
            $numberMessage          = '';
            foreach($warehouseList as $key=>$val)
            {
                if($numberResult===false)
                {
                    break;
                }
                $valNowNumber       = $val['now_number'];
                $valBillNumber      = $val['bill_number'];
                $nowNumber          = $valNowNumber - $valBillNumber;
                if($nowNumber < 0)
                {
                    $numberResult   = false;
                    $numberMessage  = $val['product_name'].'添加数量超过了库存中的数量';
                }
            }
            if($numberResult === false)
            {
                xThrow(ERR_PARAMETER, $numberMessage);
            }
            //$sn                     = 'YSD'.$_SERVER['REQUEST_TIME'].$customerId.mt_rand(1000,9999);
            $sn                     = \App\Eloquent\Ygt\WarehouseBill::getSn();
            $sendTime               = '';
            if($sendTimeDate)
            {
                $sendTime           = strtotime($sendTimeDate);
            }
            $data                   = [
                'company_id'=>$companyId,
                'sn'=>$sn,
                'customer_id'=>$customerId,
                'pre_money'=>$money,
                'money'=>0,//已收款改为0
                'pay_type'=>$payType,
                'send_time'=>$sendTime,
                'status'=>1,//未出库
            ];
            $fieldList              = WarehouseBill::$tableFieldList;
            $tableData              = WarehouseBill::setDataByTableField($data,$fieldList);
            $tableDataCheckResult   = WarehouseBill::checkDataByTableField($tableData,$fieldList);
            if($tableDataCheckResult !== true)
            {
                xThrow(ERR_PARAMETER, $tableDataCheckResult);
            }
            $warehouseBillId        = WarehouseBill::edit($tableData,'id');
            if($warehouseBillId===false)
            {
                xThrow(ERR_UNKNOWN);
            }
            //对应的入库单数量扣除,并且账单数量情况
            $customerOrderIdArr     = [];
            foreach($warehouseList as $key=>$val)
            {
                $valId              = $val['id'];
                $valNowNumber       = $val['now_number'];
                $valBillNumber      = $val['bill_number'];
                $orderId            = $val['order_id'];
                $price              = $val['price'];
                //如果有新设置的价格，取新的
                if(isset($warehousePriceList[$valId])){
                    $price = $warehousePriceList[$valId];
                }

                $money              = $valBillNumber * $price;
                $nowNumber          = $valNowNumber - $valBillNumber;
                $billNumber         = 0;
                //应收单减库存
                $where              = ['id'=>$valId];
                $updateData         = ['now_number'=>$nowNumber,'bill_number'=>$billNumber];
                Warehouse::updateOneData($where,$updateData);
                $relationData       = [
                    'user_id'=>$userId,
                    'company_id'=>$companyId,
                    'warehouse_bill_id'=>$warehouseBillId,
                    'warehouse_id'=>$valId,
                    'customer_id'=>$customerId,
                    'order_id'=>$orderId,
                    'pre_number'=>$valBillNumber,
                    'price'=>$price,
                    'money'=>$money,
                ];
                WarehouseBillRelation::insertOneData($relationData);

                //一个订单对应多个工单
                $where                  = ['id'=>$orderId];
                $order                  = \App\Eloquent\Ygt\Order::where($where)->first();
                if($order) {
                    $customerOrderId    = $order->customer_order_id;
                    if ($customerOrderId && !in_array($customerOrderId, $customerOrderIdArr)) {
                        $customerOrderIdArr[] = $customerOrderId;
                    }
                }
            }
            //生成应收单时发消息,涉及到的订单都发
            if(!empty($customerOrderIdArr))
            {
                foreach($customerOrderIdArr as $key=>$val)
                {
                    $arr                = [
                        'user_id'=>$userId,
                        'company_id'=>$companyId,
                        'foreign_key'=>$val,
                        'type_id'=>$warehouseBillId,
                        'content'=>'有一个新的交货单',
                        'theme'=>'新的交货单'
                    ];
                    $this->sendMessageByType($arr);
                }
            }
            $result                 = ['message'=>'添加成功'];
            return $result;
        } else {
            xThrow(ERR_UNKNOWN);
        }
    }
    //发消息,默认生成应收单时,销售给仓库发消息
    public static function sendMessageByType($arr,$type=0)
    {
        switch($type)
        {
            case 1:
                break;
            default:
                //生成应收单时,销售给仓库发消息
//                $arr                = [
//                    'user_id'=>'当前登录人的id',
//                    'company_id'=>'当前登录人的厂id',
//                    'foreign_key'=>'分组外键id',
//                    'type_id'=>'type_id',
//                    'content'=>'消息的内容',
//                ];
                $messageType        = 36;
                $userId             = $arr['user_id'];
                $companyId          = $arr['company_id'];
                $foreignKey         = $arr['foreign_key'];
                $typeId             = $arr['type_id'];
                $messageContent     = $arr['content'];
                $title              = '生成交货单';
                //取厂下的所有仓库员
                $appnodeId          = 3;//仓库角色
                $userList           = \App\Eloquent\Ygt\Privilege::getPrivilegeUser( $companyId, $appnodeId );
                $toUserIdArr        = [];
                foreach($userList as $key=>$val)
                {
                    $toUserIdArr[]  = $val['user_id'];
                }
                $toUserIdStr        = implode(',',$toUserIdArr);
                $messageData        = [
                    'company_id' => $companyId,
                    'privilege_id' => 0,
                    'form_user_id' => $userId,
                    'to_user_id' => $toUserIdStr,
                    'foreign_key' => $foreignKey,
                    'type' => $messageType,
                    'type_id' => $typeId,
                    'title' => $title,
                    'content' => $messageContent,
                    'type_status' => 1,
//                    'theme' => '生成发货单',
                ];
                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($messageData);

//                //给发货员发送消息
//                $appnodeId          = 12;//发货员角色
//                $userList           = \App\Eloquent\Ygt\Privilege::getPrivilegeUser( $companyId, $appnodeId );
//                $toUserIdArr        = [];
//                foreach($userList as $key=>$val)
//                {
//                    $toUserIdArr[]  = $val['user_id'];
//                }
//                $toUserIdStr        = implode(',',$toUserIdArr);
//                $messageData        = [
//                    'company_id' => $companyId,
//                    'privilege_id' => 0,
//                    'form_user_id' => $userId,
//                    'to_user_id' => $toUserIdStr,
//                    'foreign_key' => $foreignKey,
//                    'type' => $messageType,
//                    'type_id' => $typeId,
//                    'title' => $title,
//                    'content' => $messageContent,
//                    'type_status' => 1,
//                    'theme' => '生成发货单',
//                ];
//                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($messageData);

            ///////////////////////////////////////
        }
    }

    public function detail()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $billId             = request('bill_id',0);
        if( !$userInfo || !$billId)
        {
            xThrow( ERR_PARAMETER );
        }
        $where              = ['id'=>$billId];
        $info               = \App\Eloquent\Ygt\WarehouseBillMoney::getInfo($where);
        $bill               = [];

        if($info)
        {
            $bill           = $info->toArray();
//            $bill['money']      = '实收金额: '.$bill['money'];
//            $bill['pre_money']  = '预收金额: '.$bill['pre_money'];
            $bill['money']      = '¥ '.$bill['money'];
            $bill['pre_money']  = '¥'.$bill['pre_money'];

            $bill['money'] = $bill['pre_money'];


            $customerName   = \App\Engine\Customer::getNameById($bill['customer_id']);
            $bill['customer_name']  = $customerName;

            $where          = ['warehouse_bill_id'=>$info['warehouse_bill_id']];
            $relationObj    = WarehouseBillRelation::getList($where);
            $relationList   = $relationObj->toArray();
            $warehouseIdArr = $relationObj->pluck('warehouse_id');
            $where          = ['id'=>['in',$warehouseIdArr]];
            $orderList      = Warehouse::getList($where)->toArray();
            $dataList       = [];
            foreach($orderList as $key=>$val)
            {
                foreach($relationList as $k=>$v)
                {
                    if($val['order_id'] == $v['order_id'])
                    {
                        $temp                = $val;
                        $temp['number']     = $v['number'];
                        $temp['price']      = '¥'.$v['price'];
                        $temp['money']      = '¥'.$v['money'];
                        $dataList[]          = $temp;
                    }
                }
            }
            $bill['data']   = $dataList;
        }
        return $bill;
    }
}